<?php

namespace app\modules\prod\controllers;

use yii;
use yii\helpers\Json;
use app\common\Controller;
use app\common\SystemEvent;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii2mod\editable\EditableAction;
use yii2mod\rbac\filters\AccessControl;
use app\models\Region;
use app\models\RegionType;
use app\models\ProdSpec;
use app\models\ProdInst;
use app\models\ProdInstSearch;
use app\models\ProdAttrSpecRela;
use app\models\ProdAttrInst;
use app\models\UploadForm;
use app\models\Image;
//use kartik\file\FileInput;
use yii\web\UploadedFile;


use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;

class ProdInstController extends Controller
{
    
	public $module;
	public $protected_uids = [];    
	public $superadmin_uid = 0;
	public $loginRedirect = '/admin/dashboard';
	public $defaultAction = 'index';
	public function init()
	{
		parent::init();
	}


     public function actionIndex($q)
    {
        $query = Region::find();
        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),
        ]);
        $regions = $query->orderBy('region_type_id')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('index', ['pagination' => $pagination ,
        'regions' => $regions ]);

    }


    public function actionSeachprodinst($q)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = ProdInst::find()
            ->select('id, prod_name as text')
            ->where(['prod_spec_id'=>10001])
            ->andFilterWhere(['like', 'prod_name', $q])
            ->limit(12)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }

    public function actionView($id=null, $prod_spec_id=null, $prod_spec_name = null)
    {
        $topShowCnt = 0;
        $topShowss = [];

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;

        $model = $this->getProdInst($id);

        // 获取到对应图片的全部URL
        $p1 = $this->getProdAttrInstByID($id );
        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
     //Yii::trace($p1);

        //  查询所有该产品的特性值规格，主要用来取名称
        $attrSpecs = $this->getAttrSpecs($prod_spec_id);
        $attrSpecNames = [];
        foreach ($attrSpecs as $attrSpec)
        {
//            Yii::trace($attrSpec );
//            Yii::trace($attrSpec->attrSpecs );
//            Yii::trace($attrSpec->attrSpecs->id );
            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['name'] = $attrSpec->attrSpecs->attr_spec_name;

//            foreach ($attrSpec as $attrSpecs)
//            {
//                Yii::trace($attrSpecs );
//                $attrSpecNames[$attrSpecs->attrSpecs->id]['name'] = $attrSpecs->attrSpecs->attr_spec_name;
//            }
        //    $attrSpecNames[$attrSpec->attrSpecs->id]['name'] = $attrSpec->attrSpecs->attr_spec_name;
           // break;
        }

//        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//        Yii::trace($attrSpecs );
//
//        Yii::trace($attrSpecNames);
//            Yii::trace($newProdInst->attrSpec );

        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        // 组织top_show的内容
//        $topShows[$topShowCnt]['field_name']    = '详细地址';
//        $topShows[$topShowCnt]['field_values']  = $model->users->username;
//        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建用户';
        $topShows[$topShowCnt]['field_values']  = $model->users->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建时间';
        $topShows[$topShowCnt]['field_values']  = $model->create_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '修改用户';
        $topShows[$topShowCnt]['field_values']  = $model->modifyUsers->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '修改时间';
        $topShows[$topShowCnt]['field_values']  = $model->modify_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '状态';
        $topShows[$topShowCnt]['field_values']  = $model->state;
        $topShowCnt++;


        return $this->render('view',
            ['model' => $model,
                'p1' =>$p1,
                'attrSpecNames' => $attrSpecNames,
                'topShows' => $topShows,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }

    /*
     *  更新内容
     * */
    public function actionUpdate($id=null, $prod_spec_id=null, $prod_spec_name = null)
    {

        // 初始化最重要的产品实例字段
        $postModel   = new ProdInst();

        // 初始化全部的图片
        $uploadModel = new UploadForm();



        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;
        //ProdSpec::find()->select(['spec_name'])->where(['id' => $prod_spec_id])->one();

        //取到产品实例数据

  //  $model = $this->findModel($id);
        $model = new ProdInst();

        $query3 = ProdInst::find()->alias('a');
        if ($prod_spec_id==10002)
        {
            $query3->joinWith('parentProdInsts  AS g');

        }
        $query3->joinWith('regions  AS b');
        $query3->joinWith('parentRegions  AS c');


        //$query3->joinWith('superParentRegions  AS f');
        $query3->joinWith('prodAttrInsts  AS e');
        $query3->where(['a.id' => $id ]);

        $model2 = $query3->all();

//        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//           Yii::trace($model2);

        //  查询所有该产品的特性值
        $attrSpecs = $this->getAttrSpecs($prod_spec_id);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];
        $p1 = $this->getProdAttrInstByID($id );;
        $fileCnt = 0;
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['name']                   = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id']   = $attrSpec->attrSpecs->attr_spec_type_id ;

//            // 如果是图片需要构建图片的数组
//            if ($attrSpec->attrSpecs->attr_spec_type_id ==2)
//            {
//                // 取出同一个prod_id这种类型值中全部的数据，一条查询语句
//                $p1 = $this->getProdAttrInstByID($id  , $attrSpec->attrSpecs->attr_spec_id);
//               // $uploadModel->file[$attrSpec->attrSpecs->attr_spec_id][]
//            }
          //  $uploadModel->file[$fileCnt][$attrSpec->attrSpecs->attr_spec_id]
        }


//        // 获取省一级的region_type_id
//        $regions = [];
//        $queryRegions = Region::find();
//        $queryRegions->where(['region_type_id' => 2 ]);
//        foreach ( $queryRegions as $region)
//        {
//            $regions[$region->id]['region_name'] = $region->region_name;
//            $regions[$region->id]['region_type_id '] = $region->region_type_id ;
//            $regions[$region->id]['region_type_id '] = $region->id ;
//        }

        //
        //$model->load($model2);
     //  Yii::trace($model2);
    //    Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
     //   Yii::trace($model);

        foreach ( $model2 as $prodinst)
        {
//            Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&");
//
//            Yii::trace($prodinst->parentProdInsts);
//            Yii::trace($prodinst);

            $model->parent_id     = $prodinst->parent_id;
            $model->id             = $prodinst->id ;
            $model->prod_spec_id = $prodinst->prod_spec_id ;
            $model->prod_name    = $prodinst->prod_name ;
            $model->province     = $prodinst->parentRegions->parent_region_id;
            $model->city          = $prodinst->parentRegions->id;
            $model->areas         = $prodinst->areas ;
            $model->region_id       = $prodinst->region_id ;
            if ($prodinst->parentProdInsts)
            {
                $model->parentProdName = $prodinst->parentProdInsts->prod_name;
                Yii::trace($model->parentProdName);
            }

            foreach($prodinst->prodAttrInsts as $attrSpec)
            {
                $model->attrSpecs[$attrSpec->attr_spec_id]['content']              = $attrSpec->content;
                $model->attrSpecs[$attrSpec->attr_spec_id]['attr_spec_type_id'] = $attrSpecIndex[$attrSpec->attr_spec_id]['attr_spec_type_id'];
            }

            //$model->attrSpec = $prodinst->prodAttrInsts ;

            //Yii::trace($prodinst->attrSpec);

           // Yii::trace($model->attrSpec);
            //    Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&model->attrSpec&&&&&&&&&&&&&&&&&&&&&&&&");
            break;
        }



        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {


       //     $postModel->id = Yii::$app->request->post()->id;
            $postModel->modify_date        = date("Y-m-d H:i:s",time());;
            $postModel->modify_staff_id   = Yii::$app->user->id;
//            Yii::trace( Yii::$app->request->post());
//            Yii::trace("!!!&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//            Yii::trace( $postModel->id);

            //更新prod_inst
            $this->insertOrUpdateToProdInstTable($postModel, $model);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            return $this->redirect(['classify','prod_spec_id' =>$prod_spec_id]);
        }



        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        //$regionList      = $query2->orderBy('id')->all();




        return $this->render('update',
            [
                'p1' =>$p1,
                'model' => $model,
                'uploadModel' => $uploadModel,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }

    public function getAttrSpecs($prod_spec_id)
    {
        $attrSpecRela = ProdAttrSpecRela::find()->alias('f');
        $attrSpecRela->joinWith('attrSpecs  AS g');
        $attrSpecs    = $attrSpecRela->where(['prod_spec_id' => $prod_spec_id ])->all();
        return $attrSpecs;
    }



    /*
     * 为房源设置父类别，也就是楼盘，进入楼盘列表页
     * */
    public function actionSelectParent($prod_spec_id=null, $parent_id  = null)
    {

    }

//    public function actionClassify($prod_spec_id=null, $parent_id  = null)
//    {
//
//    }




    /*
     * @p prod_spec_id 产品规格
     *
     * */
    public function actionClassify($prod_spec_id=null, $parent_id  = null, $sub_prod_id=null)
    {

        if ($prod_spec_id==null)
        {
            $region_type_id = 1;
        }

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpec = ProdSpec::find()->select(['spec_name'])->where(['prod_spec_id' => $prod_spec_id])->one();
        $prodSpecName = $prodSpec->spec_name;

        // 查询所有该产品的特性值
        $attrSpecs    = $this->getAttrSpecs($prod_spec_id);


        // 取出区域编码对应的文字
        $regionTypes = $this->getRegionTypes();



        $searchModel = new ProdInstSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $prod_spec_id, $parent_id);

//        $searchModel = $this->module->model("ProdInstSearch");
//        $params = Yii::$app->request->getQueryParams();
//        $dataProvider = $searchModel->search($params, $prod_spec_id);

//        $dataProvider = new ActiveDataProvider([
//            'query' => $query,
//            'pagination' => [
//                'pageSize' => 10,
//            ],
//        ]);

//        $query->andFilterWhere([
//            'id' => $this->id,
//            'user_id' => $this->user_id,
//            'customer_id' => $this->customer_id,
//            'order_time' => $this->order_time,
//            'pay_time' => $this->pay_time,
//        ]);

        $today = date("Y-m-d",time());
        $regionTodayCnt = ProdInst::find()->where(['AND', ['prod_spec_id' => $prod_spec_id],['>','modify_date',$today] ])->count();
        $regionCnt      = ProdInst::find()->where(['prod_spec_id' => $prod_spec_id ])->groupBy(['region_id'])->count();

        // 通过添加过滤器来调整查询语句
        //$query->andFilterWhere(['region_type_id' => $region_type_id]);

       // $regions = $query->where('region_type_id=:region_type_id', [':region_type_id' => $region_type_id ])->orderBy('id')->all();





        return $this->render('classify',
            [
                'sub_prod_id' => $sub_prod_id,
                'parent_prod_id' =>$parent_id,
                'prod_spec_id' => $prod_spec_id,
                'prodSpecName' =>$prodSpecName,
                'regionTypes' => $regionTypes,
                'dataProvider' => $dataProvider,
                'searchModel' =>  $searchModel,
                'regionCnt' => $regionCnt,
                'attrSpecs' => $attrSpecs,
                'regionTodayCnt' => $regionTodayCnt]);

    }

    // 创建子集
    //public function actionCreateSub($region_type_id=null,$region_type_name=null)

    public function actionCreate($prod_spec_id=null, $parent_prod_id = null)
    {

        // 初始化类型
        $model = new ProdInst();

        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
//            Yii::trace("=====================              ============");
//            Yii::trace($model);
//            Yii::trace($model->parent_id);


           // $model->parent_region_id  = 0;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            $model->state               = 'ON';

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            //创建Region
            $this->insertOrUpdateToProdInstTable($model);
            return $this->redirect(['classify','prod_spec_id' =>$prod_spec_id]);
           // return   $this->redirect(Yii::app()->request->urlReferrer);
           // return  $this->redirect(Yii::$app->request->getReferrer());
            //return $this->redirect(['classify', 'region_type_id' => $region_type_id, 'region_type_name' => $region_type_name]);
        }

        // 查询所有该产品的特性规格
        $attrSpecs    = getAttrSpecs($prod_spec_id);

        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        $p1 = [];

        // 初始化全部的图片
        $uploadModel = new UploadForm();
        return $this->render('create',
                            [   'parent_prod_id' => $parent_prod_id,
                                'p1' =>$p1,
                                'model' => $model,
                                'uploadModel' => $uploadModel,
                                'prod_spec_id' =>$prod_spec_id,
                                'attrSpecs' => $attrSpecs,
                                'regionList' =>$regionList]);


    }


    public function actionSite($parent_region_id=null)
    {
        $query = new Region();
        $model = $query->getCityList($parent_region_id);

        echo Html::tag('option','选择区域', ['value'=>'empty']) ;
        foreach($model as $value=>$name)
        {
            echo Html::tag('option',Html::encode($name),array('value'=>$value));
        }


    }

    public function actionDelete($id, $prod_spec_id=null)
    {

        try{
            $this->deleteProdInst($id);
           // Yii::$app->getAuthManager()->remove($model->item);
            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
        }catch (IntegrityException $e){
            Yii::$app->session->setFlash('success', Yii::t('region', '删除失败.'));
          //  return $this->redirect(Yii::$app->request->getReferrer());
        }

        return $this->redirect(['classify','prod_spec_id' =>$prod_spec_id]);
    }

    public function deleteProdInst($id)
    {
        $prodInst = ProdInst::find()->where(['id'=>$id])->one();
        if($prodInst)$prodInst->delete();
    }


    /*通过prod-id获取全部的产品属性实例*/
    public function  getProdAttrInstByID($prod_id=null )
    {
        // 初始化最重要的产品实例字段
        //$model = new ProdAttrInst();
        $model=[];
        $query = ProdAttrInst::find()->alias('a');
        $query->joinWith('attrSpecs  AS b');
        $query->joinWith('images  AS c');


        $query->where(['a.prod_id' => $prod_id , 'b.attr_spec_type_id' => 2]);
        $models = $query->all();

        foreach ($models as $key => $values)
        {
            $model[$values->attrSpecs['attr_spec_id']][] = $values->images['url'] . $values->images['image_name'];
        }

        return $model;
    }

    /*通过prod-id获取全部的产品实例*/
    public function getProdInst($id=null)
    {
        // 初始化最重要的产品实例字段
        $model = new ProdInst();


        $query = ProdInst::find()->alias('a');
        $query->joinWith('users  AS f');
        $query->joinWith('modifyUsers  AS g');
        $query->joinWith('regions  AS b');
        $query->joinWith('parentRegions  AS c');
        $query->joinWith('prodAttrInsts  AS e');
        $query->where(['a.id' => $id ]);
        $models = $query->all();

//        $model
//        $models->province     = $models->parentRegions->parent_region_id;
//        $models->city          = $models->parentRegions->id;
//        foreach($models->prodAttrInsts as $attrSpec)
//        {
//            $models->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
//        }
//
//        return $models;
        $model = $models[0];
        foreach($models[0]->prodAttrInsts as $attrSpec)
        {
            $model->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
        }

//        foreach ( $models as $prodinst)
//        {
//           // Yii::trace("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
//            $model->id             = $prodinst->id ;
//            $model->prod_spec_id = $prodinst->prod_spec_id ;
//            $model->prod_name    = $prodinst->prod_name ;
//
//
//
//            $model->areas         = $prodinst->areas ;
//            $model->region_id    = $prodinst->region_id ;
//
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//
//
//            $model->province     = $prodinst->parentRegions->parent_region_id;
//            $model->city          = $prodinst->parentRegions->id;
//
//            foreach($prodinst->prodAttrInsts as $attrSpec)
//            {
//                $model->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
//            }
//
//            break;
//        }

        return $model;
    }

    // 取出父级区域编码对应的文字
    public function getParentRegionTypes($parent_region_id)
    {
        $query2 = Region::find();
        $query2->where(['parent_region_id' => $parent_region_id ]);
        $regionList      = $query2->orderBy('id')->all();
        return $regionList;
    }

    // 取出区域编码对应的文字
    public function getRegionTypes()
    {

        $regionTypes = [];
        $query = RegionType::find()->alias('a');
        $queryRegionTypes = $query->all();
        foreach ($queryRegionTypes as $queryRegionType)
        {
            $regionTypes[$queryRegionType->id] = $queryRegionType->region_type_name;
        }

        return $regionTypes;
    }

    /**
     * 新增或者修改 role table
     * @param $newRole
     * @param string $oldRole
     */
    public function insertOrUpdateToProdInstTable( $newProdInst, $oldProdInst=null)
    {
        $i = 0;                   // 批量插入的数量
        $insertProdAttrs =[];     // 批量插入的数组
        $oldProdAttrInst = [];  // 旧的产品特性实例

        //$should = 0;//1=insert,2=update,0=nothing to do
        //$role   = null;
        if($oldProdInst)
        {
            Yii::trace("************************************************************");
            //Yii::trace($newProdInst);


            $prodInst = ProdInst::find()->where(['id'=>$newProdInst->id])->one();

            $prodInst->modify_date        = date("Y-m-d H:i:s",time());;
            $prodInst->modify_staff_id   = Yii::$app->user->id;
            $prodInst-> prod_name         = $newProdInst->prod_name;
            $prodInst-> prod_spec_id     = $newProdInst->prod_spec_id;
            $prodInst-> parent_id         = $newProdInst->parent_id;
            $prodInst-> region_id         = $newProdInst->region_id ;
            $prodInst-> price_id          = $newProdInst->price_id ;

            $prodInst->save();

            // 处理图片

//            $uploadModel = new UploadForm();
//            $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[6]');
//
////            Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&uploadModel&&&&&&&&&&&&&&&&&&&&&&&&");
////            Yii::trace($uploadModel);
////            Yii::trace($uploadModel->validate());
//
//            //&& $uploadModel->validate()
//            if ($uploadModel->file )
//            {
//
//                foreach ($uploadModel->file as $file)
//                {
//
//                    Yii::trace("===============================");
//                    Yii::trace($file->baseName);
//                    $filelName = time().rand(100,999);
//                    $file->saveAs('uploads/' . $filelName. '.' . $file->extension);
//                }
//
//            }

//            Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//            Yii::trace($newProdInst->attrSpec );
        //Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
        //Yii::trace($newProdInst->id);

            // 填写产品特性值
            // 检查产品特性值是否有值，或者有变化， 有变化就更新，原来没有值插入值

            // 构成标准值
            foreach ($prodInst->prodAttrInsts as $key => $prodAttrInst)
            {
                $oldProdAttrInst[$prodAttrInst->attr_spec_id]['content'] = $prodAttrInst->content;
                $oldProdAttrInst[$prodAttrInst->attr_spec_id]['id']       = $prodAttrInst->id;


//                Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//                Yii::trace($key);
//                Yii::trace($prodAttrInst);
            }
//            Yii::trace("********************************************");
//            Yii::trace($newProdInst);

            foreach ($newProdInst->attrSpec as $key => $attrSpec)
            {
                // 如果实例不存在则新增
                if (!$oldProdAttrInst[$key])
                {
                    Yii::trace("#############################################");
                    //处理图片类型
                    if ($attrSpec['attr_spec_type_id']==2)
                    {
                        // 初始化图片对象类
                        $uploadModel = new UploadForm();

                        //取出对应的图片句柄
                        $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');

                        // 审核是否有图片 & 图片是否符合校验标准
                        if ($uploadModel->file  && $uploadModel->validate())
                        {
                            $imageIndex = 0;

                            // 将图片插入表格
                            foreach ($uploadModel->file as $file)
                            {
//                                Yii::trace("===============================");
//                                Yii::trace($file->baseName);

                                $url = '/uploads/';
                                $filelName =  time().rand(100,999) . '.' . $file->extension;
                                $file->saveAs($url . $filelName);

                                // 将图片地址存入数据库，记录该图片的来源时间和上传人
                                $image                = new Image();
                                $image->image_name  = $filelName;
                                $image->url          = $url;
                                $image->create_date = date("Y-m-d H:i:s",time());
                                $image->staff_id     = Yii::$app->user->id;

                                $image->save();

                                // 获得id
                                $imageId = $image->attributes['id'];

                                $insertProdAttrs[$i][] = $prodInst->id;
                                $insertProdAttrs[$i][] = $key;
                                $insertProdAttrs[$i][] = $imageId ;
                                $insertProdAttrs[$i][] = $imageIndex ;

                                $i++;
                                $imageIndex++;

                                // 构成属性值的更新或者插入语句
                            }

                        }
                    }
                    else
                    {
                        // 如果值为空也不插入
                        if(!$attrSpec['content'])
                        {
                            continue;
                        }

                        $content = $attrSpec['content'] ;

                        $insertProdAttrs[$i][] = $prodInst->id;
                        $insertProdAttrs[$i][] = $key;
                        $insertProdAttrs[$i][] = $attrSpec['content'] ;
                        $insertProdAttrs[$i][] = 0 ;
                        $i++;
                    }




//                        $image =  UploadedFile::getInstance($newProdInst, "attrSpec[' . $key . ']['content']");
//
//                        Yii::trace($image);
//
//                        $ext = $image->getExtension();
//                        $imageName = time().rand(100,999).'.'.$ext;
//                        $image->saveAs('uploads/'.$imageName);//设置图片的存储位置
//
//                        $content = '/uploads/'.$imageName;



                }
                else//存在的话看下数值是否一致，不一致则更新
                {
                    //
                    if ($oldProdAttrInst[$key]['content']!=$attrSpec['content'])
                    {
                        ProdAttrInst::updateAll(['content' => $attrSpec['content']], ['id' => $oldProdAttrInst[$key]['id']]);
//.                        $model = ProdAttrInst::findOne($oldProdAttrInst[$key]['id']);
//                        $model->content = $content;
//                        $count = $model->update(array('content'));
                    }

                }

            }



        }
        else
        {

//            $image =  UploadedFile::getInstance($model,'数据表存储字段');
//            $ext = $image->getExtension();
//            $imageName = time().rand(100,999).'.'.$ext;
//            $image->saveAs('uploads/'.$imageName);//设置图片的存储位置


            //新增
            /*$role = Region::find()->where(['name'=>$newRegion])->one();
            if(!$role){
                $should = 1;
            }*/
            $newProdInst->save();

            // 获得id
            $id = $newProdInst->attributes['id'];



            foreach ($newProdInst->attrSpec as $key => $attrSpec   )
            {


                // 如果值为空也不插入
                if(!$attrSpec['content'])
                {
                    continue;
                }

                $content = $attrSpec['content'] ;

              //  Yii::trace("#############################################");
                //处理图片类型
                if ($attrSpec['attr_spec_type_id']==2)
                {
//                                  Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//                     Yii::trace($key);

                    $image =  UploadedFile::getInstance($newProdInst, "attrSpec[' . $key . ']['content']");

//                    Yii::trace($image);

                    $ext = $image->getExtension();
                    $imageName = time().rand(100,999).'.'.$ext;
                    $image->saveAs('uploads/'.$imageName);//设置图片的存储位置

                    $content = '/uploads/'.$imageName;
                }



                $insertProdAttrs[$i][] = $id;
                $insertProdAttrs[$i][] = $key;
                $insertProdAttrs[$i][] = $content ;
                $insertProdAttrs[$i][] = 0 ;
                $i++;

            }


//            $prodAttrInst = new ProdAttrInst();
//            $prodAttrInst->prod_id = $id;
            //将属性插入产品属性实例表
        }

        // 如果插入数组不为空则执行插入
        if (!empty($insertProdAttrs))
        {
            Yii::$app->db->createCommand()->batchInsert(ProdAttrInst::tableName(), ['prod_id','attr_spec_id','content','sort'], $insertProdAttrs)->execute();
        }



    }

//    public function actionIndex()
//    {
//        $menus = SystemEvent::GetAdminMenu();
//        if(Yii::$app->request->isAjax){
//            return '<script>OA_Menus='.Json::encode($menus).'</script>';
//        }
//        return $this->renderPartial('index',['menus'=>$menus]);
//    }
}
